// ==UserScript==
// @name				HWM - Timers
// @namespace			figey_hwm_
// @description			Timers for hp, mana, guilds
// @version				0.1.0
// @run-at				document-end
// @grant				GM_deleteValue
// @grant				GM_getValue
// @grant				GM_info
// @grant				GM_listValues
// @grant				GM_notification
// @grant				GM_setValue
// @noframe
// @require				https://notabug.org/figey/localDataStorage/raw/8018b121fb20340d325f45999a308b02b8d761e1/localDataStorage-1.2.0.trim.js
// @require				https://notabug.org/figey/hwm_scripts/raw/59e98a179ba73cc408884238fa4c7c0285622194/src/core.js
// @include				/^https?:\/\/(www\.)?(heroeswm\.ru|lordswm\.com)\/.+/
// @exclude				/^https?:\/\/(www\.)?(heroeswm\.ru|lordswm\.com)\/(cgame|login)\.php.*/
// @exclude				/^https?:\/\/(www\.)?(heroeswm\.ru|lordswm\.com)\/forum.*/
// @exclude				/^https?:\/\/(www\.)?(heroeswm\.ru|lordswm\.com)\/war.*/
// ==/UserScript==

/**
 * Init
 */
const notify = new Notify(GM_info.script.name, '');

const Timer = {
	/**
	 * Array for timers
	 */
	data: [
		{
			name: 'timerHP',
			value: 'HP',
			onclick: function(event){
				if( heart < 100 ){
					const xhr = runXHR('GET', '/tavern.php?action=free_hp_drink', true );
					xhr.onload = function(){
						if( xhr.status == 200 && xhr.responseURL.match(/tavern\.php/) 
							&& xhr.responseText.match(/href="tavern_games\.php"/)
							&& xhr.responseText.match(/var heart=(\d+)/) && xhr.responseText.match(/var heart=(\d+)/)[1] == 100
						){
							notify.send({
								body: 'Ваше здоровье полностью восстановилось!',
								tag: 'timerHP',
								timeout: 15000,
								onclick: function(event){
									event.preventDefault();
									parent.focus();
									window.focus();
									event.target.close();
								}
							});
							ls.set('timerHP', 0);
							location.reload();
						} else {
							notify.send({
								body: 'Ошибка при попытке восст. здоровье!',
								tag: 'timerHP',
								timeout: 15000,
								onclick: function(event){
									event.preventDefault();
									parent.focus();
									window.focus();
									event.target.close();
								}
							});
						}
					};
				} else {
					alert('Ваше здоровье уже полное');
				}
			},
			notify: function(){
				notify.send({
					body: 'Ваше здоровье полностью восстановилось!',
					tag: 'timerHP',
					timeout: 15000,
					onclick: function(event){
						event.preventDefault();
						parent.focus();
						window.focus();
						event.target.close();
						location.reload();
					}
				});
			}
		},
		{
			name: 'timerHG',
			value: 'ГО',
			onclick: function(event){
				if( location.pathname.match(/map\.php/) ){
					location.reload();
				} else {
					location.assign('/map.php');
				}
			},
			notify: function(){
				notify.send({
					body: 'Обнаружены новые монстры для охоты!',
					tag: 'timerHG',
					timeout: 15000,
					onclick: function(event){
						event.preventDefault();
						parent.focus();
						window.focus();
						event.target.close();
						location.assign('/map.php');
					}
				});
			}
		},
		{
			name: 'timerLG',
			value: 'ГР',
			onclick: function(event){
				location.assign('/map.php?st=sh');
			},
			notify: function(){
				notify.send({
					body: 'Вы безработный!',
					tag: 'timerLG',
					timeout: 15000,
					onclick: function(event){
						event.preventDefault();
						parent.focus();
						window.focus();
						event.target.close();
						location.assign('/map.php?st=sh');
					}
				});
			}
		},
		{
			name: 'timerMG',
			value: 'ГН',
			onclick: function(event){
				if( location.pathname != '/mercenary_guild.php' ){
					location.assign('/mercenary_guild.php');
				}
			},
			notify: function(){
				notify.send({
					body: 'У нас есть новое задание!',
					icon: 'https://dcdn1.heroeswm.ru/i/gn_face.png',
					tag: 'timerMG',
					timeout: 15000,
					onclick: function(event){
						// TODO check sector?
						event.preventDefault();
						parent.focus();
						window.focus();
						event.target.close();
						location.assign('/mercenary_guild.php');
					}
				});
			}
		},
	],

	/**
	 * Create table for timers
	 */
	init(){
		// create DOM table
		const table = document.createElement('table');
		document.body.insertBefore(table,document.body.firstChild);
		table.style = 'z-index: 1; -moz-user-select: none; user-select: none; position: absolute; top: 0px; left: 50%; background: #757575;';
		const tr = document.createElement('tr');
		this.data.forEach(function(t){
			const td = document.createElement('td');
			td.align = 'center';
			td.style = 'color: rgb(255, 71, 0); cursor: pointer; font-size: 14; outline: 2px groove black;  width: 30px;';
			td.textContent = t.value;
			td.onclick = t.onclick;

			const td2 = document.createElement('td');
			td2.id = GM_info.script.namespace + t.name + '_value';
			td2.align = 'center';
			td2.style = 'color: #f5c140; cursor: default; font-size: 14; font-weight: bold; outline: 2px groove black; width: 40px;';
			tr.append(td, td2);
		});
		table.appendChild(tr);

		// fix table position by half width
		table.style.marginLeft = (-0.5 * table.offsetWidth).toString() + 'px';

		// check if timers exist in localDataStorage
		this.data.forEach(function(t){
			if( typeof ls.get(t.name) != 'number' ){
				log.info(t.name + ' not exists');
				ls.set(t.name, 0);
			}
		});
	},

	/**
	 * Start timer count if needed
	 */
	countDown(){
		this.data.forEach(function(t){
			const spanTimerId = GM_info.script.namespace + t.name + '_value';
			let timeExpire = ls.get(t.name);
			const timeNow = Date.now();
			// check if timer expire
			if( timeExpire != 0 ){
				if( timeNow > timeExpire + 1000 ){
					ls.set(t.name, 0);
					timeExpire = 0;
					t.notify();
				} else {
					timeExpire -= timeNow;
				}
			} else {
				// TODO need do anything?
			}
			// show left time
			const timerValue = document.getElementById(spanTimerId);
			if( timerValue )
				timerValue.innerHTML = extractTime(new Date(timeExpire));
		});
		setTimeout(this.countDown.bind(this), 1000);
	},
};

/**
 * run timers
 */
Timer.init();
Timer.countDown();

/**
 * HP
 */
if( document.body.innerHTML.match(/var heart=(\d+)/) ){
	const h_perc = document.body.innerHTML.match(/var heart=(\d+)/)[1];
	if( h_perc < 100 && ls.get('timerHP') == 0 ){
		const h_time = document.body.innerHTML.match(/var time_heart=(\d+)/)[1];
		const remainTime = (100-h_perc)*h_time/100;
		ls.set('timerHP', Date.now() + 1000*remainTime);
	}
}

/**
 * Hunter guild
 */
if( location.pathname.match('map.php') ){
	if( document.body.innerHTML.match(/var Delta2 = (\d+)/) ){
		ls.set('timerHG', Date.now() + 1000*document.body.innerHTML.match(/var Delta2 = (\d+)/)[1]);
	} else {
		ls.set('timerHG', 0);
	}
}

/**
 * Mercenary guild
 */
if( location.pathname.match('mercenary_guild.php') ){
	const quest = mercenaryQuestStatus(document.body.innerHTML);
	switch(quest.status){
		case 'done':
		case 'fail':
			ls.set('timerMG', Date.now() + 1000*60*quest.time);
			break;
		case 'old':
		case 'new':
			ls.set('timerMG', 0);
			break;
		case 'wait':
			// correct timer if needed
			if( Math.abs(ls.get('timerMG') - ( Date.now() + 1000*60*quest.time ) ) > 1000*60 ){
				log.warn('Correcting MG timer');
				ls.set('timerMG', Date.now() + 1000*60*quest.time);
			}
			break;
		default:
			log.error('unknown mercenary quest status: ' + quest.status);
			break;
	}
}

/**
 * LG
 */
if( location.pathname == '/object_do.php' && document.body.textContent.match(/(You have successfully enrolled|Вы устроены на работу)/) ){
	ls.set('timerLG', Date.now() + 1000*3600);
} else if( location.pathname == '/home.php' && ls.get('timerLG') == 0 ){
	let workTime;
	if( workTime = /object\-info.php.+pl\_info\.php\?id=(\d+)\D+(\d+)\:(\d+)\<\/td\>/.exec(document.body.innerHTML) ){
		const serverTime = document.body.innerHTML.match(/(\d+)\:(\d+)\,\s(\d+)/);
		if( serverTime ){
			let serverDate = new Date(0,0, +serverTime[1] < +workTime[2] ? 1 : 0, serverTime[1], serverTime[2]);
			let workDate = new Date(0,0,0,workTime[2],workTime[3]);
			ls.set('timerLG', Date.now() + ( workDate - serverDate ) + 3600000);
		}
	} else if( workTime = /object\-info.php.+pl\_info\.php\?id=(\d+)\D+(\d+)\D+\<\/td\>/.exec(document.body.innerHTML) ){
		ls.set('timerLG', Date.now() + 60000 * workTime[2] );
	}
}

/**
 * Hide hp and mana bar
 */
[ document.getElementById('heart'), document.getElementById('mana') ].forEach(function(bar){
	if( bar ){
		getParentByTagName(bar, 'td', 2).remove();
	}
});
